<template>
	<view class="uni-container">
		<uni-forms ref="form" :model="formData" validateTrigger="bind">
			<uni-forms-item name="category_id" label="商品分类">
				<uni-data-select :localdata="categoriesData" v-model="formData.category_id" placeholder="选择商品分类">
				</uni-data-select>
			</uni-forms-item>
			<uni-forms-item name="name" label="商品名称">
				<uni-easyinput placeholder="商品名称" v-model="formData.name" trim="both"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="crossed_price" label="划线价格">
				<uni-easyinput placeholder="划线价格，只做展示用,100=1元" type="number"
					v-model="formData.crossed_price"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item style="display: none;" name="orig_suks">
			</uni-forms-item>
			<uni-forms-item name="suks" label="商品规格">
				<view class="product-management">
					<view v-for="(spec, specIndex) in specs" :key="specIndex" class="spec-item mb-30">
						<view class="flex-dir-row flex-y-center ">
							<uni-easyinput @blur="saveProduct(0)" v-model="spec.name" placeholder="规格名称"
								class="f-28 spec-name-input" />
							<button @click="deleteSpec(specIndex,0)" class="delete-spec-button f-28">删除规格</button>
						</view>
						<view class="flex-dir-row  flex-y-center flex-x-start flex-wrap spec-value-list">
							<view v-for="(value, valueIndex) in spec.values" :key="valueIndex"
								class="value-item mt-30 f-28 mr-30">
								<uni-easyinput @blur="saveProduct(0)" @clear="deleteValue(specIndex, valueIndex,0)"
									v-model="value.name" placeholder="规格值" class="value-input-spec" />
							</view>
							<view style="margin-top: 20rpx;">
								<button @click="addValue(specIndex,0)" class="btn-normal mt-30 col-2979ff  f-28">+
									新增规格值</button>
							</view>
						</view>

					</view>

					<button @click="addSpec(0)" class="add-spec-button mt-30">新增规格</button>

					<view>商品价格：</view>
					<table class="combinations-table">
						<tr>
							<th v-for="(spec, specIndex) in specs" :key="specIndex">{{ spec.name }}</th>
							<th>
								<view>价格</view>
								<button class="input-all-button" @click="setAllPrices(0)">一键填充</button>
							</th>
							<th>
								<view>库存</view>
								<button class="input-all-button" @click="setAllInventory(0)">一键填充</button>
							</th>
							<th>
								<view>商品图</view>
							</th>
						</tr>
						<tr v-for="(combination, combinationIndex) in formData.suks" :key="combinationIndex">
							<td v-for="(value, valueIndex) in combination.specs" :key="valueIndex">{{ value }}
							</td>
							<td><input v-model.number="combination.price" type="number" placeholder="价格"
									class="price-input" /></td>
							<td><input v-model="combination.inventory" type="number" placeholder="库存"
									class="price-input" /></td>
							<td><cloud-image placeholder="规格图" v-model="combination.goods_thumb"></cloud-image></td>
						</tr>
					</table>
					<!-- <button @click="saveProducts" class="add-spec-button mt-30">保存</button> -->
				</view>
			</uni-forms-item>
			<uni-forms-item name="goods_services" label="商品服务">
				<uni-easyinput @blur="clickservices" @clear="clickservices" placeholder="多个服务用空格分割,例:七天无理由 30天包换"
					v-model="services"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="freight" label="是否包邮">
				<switch @change="binddata('freight', $event.detail.value)" :checked="formData.freight"></switch>
			</uni-forms-item>
			<uni-forms-item v-if="!formData.freight" name="freight_amount" label="运费金额">
				<uni-easyinput placeholder="运费金额,100=1元" type="number"
					v-model="formData.freight_amount"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="goods_desc" label="商品详情">
				<Tinymce ref="editor" v-model="formData.goods_desc" :width="860" :height="400" />
			</uni-forms-item>
			<uni-forms-item name="goods_thumb" label="缩略图片">
				<cloud-image placeholder="缩略图，用于在列表或搜索结果中预览显示" v-model="formData.goods_thumb"></cloud-image>
			</uni-forms-item>
			<uni-forms-item name="goods_banner_imgs" label="展示图片">
				<uni-file-picker file-mediatype="image" :limit="5" return-type="array"
					v-model="formData.goods_banner_imgs"></uni-file-picker>
			</uni-forms-item>
			<uni-forms-item name="videos" label="展示视频">
				<uni-file-picker file-mediatype="video" :limit="1" return-type="array"
					v-model="formData.videos"></uni-file-picker>
			</uni-forms-item>
			<uni-forms-item name="total_sell_count" label="总销量">
				<uni-easyinput placeholder="总销量" type="number" v-model="formData.total_sell_count"></uni-easyinput>
			</uni-forms-item>
			<!-- <uni-forms-item name="remain_count" label="库存数量">
				<uni-easyinput placeholder="库存数量" type="number" v-model="formData.remain_count"></uni-easyinput>
			</uni-forms-item> -->
			<uni-forms-item name="is_on_sale" label="是否上架">
				<switch @change="binddata('is_on_sale', $event.detail.value)" :checked="formData.is_on_sale"></switch>
			</uni-forms-item>
			<uni-forms-item name="is_best" label="首页推荐">
				<switch @change="binddata('is_best', $event.detail.value)" :checked="formData.is_best"></switch>
			</uni-forms-item>
			<uni-forms-item name="vip_goods" label="权益商品">
				<view style="display: flex;flex-direction: row;align-items: center;">
					<view style="margin-right: 50rpx;">
						<switch @change="binddatas" :checked="vipss"></switch>
					</view>
					<uni-data-checkbox v-if="vipss" v-model="formData.vip_goods" :localdata="sex"></uni-data-checkbox>
				</view>
			</uni-forms-item>
			<uni-forms-item name="is_new" label="参与秒杀">
				<switch @change="binddata('is_new', $event.detail.value)" :checked="formData.is_new"></switch>
			</uni-forms-item>
			<uni-forms-item style="display: none;" name="orig_fs_suks">
			</uni-forms-item>
			<uni-forms-item name="fs_suks" label="秒杀规格">
				<view class="product-management">
					<view v-for="(specc, specIndexl) in vipspecs" :key="specIndexl" class="spec-item mb-30">
						<view class="flex-dir-row flex-y-center ">
							<uni-easyinput @blur="saveProduct(1)" v-model="specc.name" placeholder="规格名称"
								class="f-28 spec-name-input" />
							<button @click="deleteSpec(specIndexl,1)" class="delete-spec-button f-28">删除规格</button>
						</view>
						<view class="flex-dir-row  flex-y-center flex-x-start flex-wrap spec-value-list">
							<view v-for="(valuez, valueIndexl) in specc.values" :key="valueIndexl"
								class="value-item mt-30 f-28 mr-30">
								<uni-easyinput @blur="saveProduct(1)" @clear="deleteValue(specIndexl, valueIndexl,1)"
									v-model="valuez.name" placeholder="规格值" class="value-input-spec" />
							</view>
							<view style="margin-top: 20rpx;">
								<button @click="addValue(specIndexl,1)" class="btn-normal mt-30 col-2979ff  f-28">+
									新增规格值</button>
							</view>
						</view>

					</view>

					<view class="flex-dir-row">
						<button style="background-color: #00ce60" @click="obtainData"
							class="add-spec-button mt-30">获取商品规格</button>
						<button @click="addSpec(1)" class="add-spec-button mt-30">新增规格</button>
					</view>

					<view>商品价格：</view>
					<table class="combinations-table">
						<tr>
							<th v-for="(speca, specIndexsq) in vipspecs" :key="specIndexsq">{{ speca.name }}</th>
							<th>
								<view>价格</view>
								<button class="input-all-button" @click="setAllPrices(1)">一键填充</button>
							</th>
							<th>
								<view>库存</view>
								<button class="input-all-button" @click="setAllInventory(1)">一键填充</button>
							</th>
							<th>
								<view>商品图</view>
							</th>
						</tr>
						<tr v-for="(combinationq, combinationIndexx) in formData.fs_suks" :key="combinationIndexx">
							<td v-for="(valueq, valueIndexl) in combinationq.specs" :key="valueIndexl">{{ valueq }}
							</td>
							<td><input v-model.number="combinationq.price" type="number" placeholder="价格"
									class="price-input" /></td>
							<td><input v-model="combinationq.inventory" type="number" placeholder="库存"
									class="price-input" /></td>
							<td><cloud-image placeholder="规格图" v-model="combinationq.goods_thumb"></cloud-image></td>
						</tr>
					</table>
					<!-- <button @click="saveProducts" class="add-spec-button mt-30">保存</button> -->
				</view>
			</uni-forms-item>
			<uni-forms-item name="is_hot" label="热销商品">
				<switch @change="binddata('is_hot', $event.detail.value)" :checked="formData.is_hot"></switch>
			</uni-forms-item>
			<view class="uni-button-group">
				<button type="primary" class="uni-button" style="width: 100px;" @click="submit">提交</button>
				<navigator open-type="navigateBack" style="margin-left: 15px;">
					<button class="uni-button" style="width: 100px;">返回</button>
				</navigator>
			</view>
		</uni-forms>
	</view>
</template>

<script>
	import {
		validator
	} from '../../js_sdk/validator/opendb-mall-goods.js';
	import Tinymce from '@/components/Tinymce'

	const db = uniCloud.database();
	const dbCmd = db.command;
	const dbCollectionName = 'opendb-mall-goods';

	function getValidator(fields) {
		let result = {}
		for (let key in validator) {
			if (fields.includes(key)) {
				result[key] = validator[key]
			}
		}
		return result
	}



	export default {
		components: {
			Tinymce,
		},
		data() {
			let formData = {
				"category_id": "",
				"name": "",
				"crossed_price": null,
				"goods_services": [],
				"freight": null,
				"freight_amount": null,
				"goods_desc": "",
				"goods_thumb": "",
				"goods_banner_imgs": [],
				"videos": [],
				"total_sell_count": null,
				"remain_count": null,
				"comment_count": null,
				"is_on_sale": null,
				"is_best": null,
				"is_new": null,
				"is_hot": null,
				"suks": [],
				"orig_suks": [],
				"fs_suks": [],
				"orig_fs_suks": [],
				"vip_goods": ""
			}
			return {
				formData,
				formOptions: {},
				services: "",
				specs: [],
				vipspecs: [],
				rules: {
					...getValidator(Object.keys(formData))
				},
				vipss: false,
				sex: [{
						text: "vip",
						value: 'vip'
					},
					{
						text: "svip",
						value: 'svip'
					}
				],
				categoriesData: [],
			}
		},
		onLoad(e) {
			if (e.id) {
				const id = e.id
				this.formDataId = id
				this.getDetail(id)
			}
		},
		onReady() {
			this.categoriesList()
			this.$refs.form.setRules(this.rules)
		},
		methods: {
			categoriesList() {
				db.collection("opendb-mall-categories").where({
					parent_id: db.command.neq('')
				}).field("_id as value,name as text,parent_id").get().then((res) => {
					this.categoriesData = res.result.data
				})
			},
			binddatas(e) {
				this.vipss = e.detail.value;
				if (this.vipss == false) {
					this.formData.vip_goods = "";
				}
			},
			binddata(e, a) {
				if (e == 'is_new') {
					this.formData.is_new = a
				} else if (e == 'freight') {
					this.formData.freight = a
				} else if (e == 'is_on_sale') {
					this.formData.is_on_sale = a
				} else if (e == 'is_best') {
					this.formData.is_best = a
				} else if (e == 'is_hot') {
					this.formData.is_hot = a
				}
			},
			clickservices() {
				this.formData.goods_services = this.services.split(" ");
			},

			addSpec(e) {
				if (e == 0) {
					this.specs.push({
						name: '',
						values: [{
							name: ''
						}]
					});
				} else if (e == 1) {
					this.vipspecs.push({
						name: '', //规格名称
						//规格值（价格库存等）
						values: [{
							name: ''
						}]
					});
				}
			},
			addValue(specIndex, e) {
				if (e == 0) {
					this.specs[specIndex].values.push({
						name: ''
					});
				} else if (e == 1) {
					this.vipspecs[specIndex].values.push({
						name: ''
					});
				}
			},
			deleteSpec(specIndex, e) {
				if (e == 0) {
					this.specs.splice(specIndex, 1);
				} else if (e == 1) {
					this.vipspecs.splice(specIndex, 1);
				}
			},
			deleteValue(specIndex, valueIndex, e) {
				if (e == 0) {
					this.specs[specIndex].values.splice(valueIndex, 1);
				} else if (e == 1) {
					this.vipspecs[specIndex].values.splice(valueIndex, 1);
				}
			},
			saveProduct(e) {
				// 生成规格组合及其对应的价格和库存
				if (e == 0) {
					this.formData.suks = this.generateCombinations(0);
				} else if (e == 1) {
					this.formData.fs_suks = this.generateCombinations(1);
				}

				// 将商品规格、规格组合、价格和库存保存到数据库或进行其他处理
				// console.log(this.specs);
				// console.log(this.formData.suks);
			},
			generateCombinations(e) {
				const combinations = [];
				this.generateCombination(0, [], combinations, e);
				return combinations;
			},
			generateCombination(specIndex, currentCombination, combinations, e) {
				if (e == 0) {
					if (specIndex === this.specs.length) {
						combinations.push({
							specs: currentCombination,
							price: null,
							inventory: null,
							goods_thumb: ''
						});
						return;
					}

					const values = this.specs[specIndex].values;
					for (const value of values) {
						const newCombination = [...currentCombination, value.name];
						this.generateCombination(specIndex + 1, newCombination, combinations, 0);
					}
				} else if (e == 1) {
					if (specIndex === this.vipspecs.length) {
						combinations.push({
							specs: currentCombination,
							price: null,
							inventory: null,
							goods_thumb: ''

						});
						return;
					}

					const values = this.vipspecs[specIndex].values;
					for (const value of values) {
						const newCombination = [...currentCombination, value.name];
						this.generateCombination(specIndex + 1, newCombination, combinations, 1);
					}
				}
			},
			//获取商品规格
			obtainData() {
				//这里使用JSON.parse(JSON.stringify(this.specs))进行深度拷贝，防止共享数据源（共享数据源例：直接使用this.vipspecs = this.specs，而后input更改其中一个的值时，另一个也会发生变化）
				this.vipspecs = JSON.parse(JSON.stringify(this.specs));
				this.formData.fs_suks = JSON.parse(JSON.stringify(this.formData.suks));
			},

			// 一键输入价格
			setAllPrices(e) {
				if (e == 0) {
					const firstPrice = this.formData.suks[0].price;
					for (const combinationq of this.formData.suks) {
						combinationq.price = firstPrice;
					}
				} else if (e == 1) {
					const firstPrice = this.formData.fs_suks[0].price;
					for (const combinationq of this.formData.fs_suks) {
						combinationq.price = firstPrice;
					}
				}
			},

			// 一键输入库存
			setAllInventory(e) {
				if (e == 0) {
					const firstInventory = this.formData.suks[0].inventory;
					for (const combinationq of this.formData.suks) {
						this.$set(combinationq, 'inventory', firstInventory);
					}
				} else if (e == 1) {
					const firstInventory = this.formData.fs_suks[0].inventory;
					for (const combinationq of this.formData.fs_suks) {
						this.$set(combinationq, 'inventory', firstInventory);
					}
				}
			},

			/**
			 * 验证表单并提交
			 */
			submit() {
				uni.showLoading({
					mask: true
				})
				this.$refs.form.validate().then((res) => {
					res.suks = this.formData.suks
					res.orig_suks = this.specs
					res.fs_suks = this.formData.fs_suks
					res.orig_fs_suks = this.vipspecs
					return this.submitForm(res)
				}).catch(() => {}).finally(() => {
					uni.hideLoading()
				})
			},

			/**
			 * 提交表单
			 */
			submitForm(value) {
				// 使用 clientDB 提交数据
				return db.collection(dbCollectionName).doc(this.formDataId).update(value).then((res) => {
					uni.showToast({
						title: '修改成功'
					})
					this.getOpenerEventChannel().emit('refreshData')
					setTimeout(() => uni.navigateBack(), 500)
				}).catch((err) => {
					uni.showModal({
						content: err.message || '请求服务失败',
						showCancel: false
					})
				})
			},

			/**
			 * 获取表单数据
			 * @param {Object} id
			 */
			getDetail(id) {
				uni.showLoading({
					mask: true
				})
				db.collection(dbCollectionName).doc(id).field(
					"category_id,name,vip_goods,crossed_price,goods_services,freight,freight_amount,goods_desc,goods_thumb,goods_banner_imgs,videos,total_sell_count,orig_suks,orig_fs_suks,remain_count,comment_count,is_on_sale,is_best,is_new,fs_is_new,is_hot,suks,fs_suks"
				).get().then((res) => {
					const data = res.result.data[0]
					if (data) {
						console.log(data.suks)
						this.formData = data
						// const uniqueTitles = [...new Set(data.suks.map((suk) => suk.specs[0]))];
						// console.log(uniqueTitles)

						this.specs = data.orig_suks
						this.vipspecs = data.orig_fs_suks
						for (let i = 0; i < this.formData.goods_services.length; i++) {
							if (i == this.formData.goods_services.length - 1) {
								this.services += this.formData.goods_services[i]
							} else {
								this.services += this.formData.goods_services[i] + ' '
							}
						}
					}
				}).catch((err) => {
					uni.showModal({
						content: err.message || '请求服务失败',
						showCancel: false
					})
				}).finally(() => {
					uni.hideLoading()
				})
			}
		}
	}
</script>
<style>
	.flex-dir-row {
		display: flex;
		flex-direction: row;
	}

	.flex-dir-column {
		display: flex;
		flex-direction: column;
	}

	.flex-y-center {
		align-items: center;
	}

	.flex-x-between {
		justify-content: space-between;
	}

	.flex-x-start {
		justify-content: space-start;
	}

	.flex-x-end {
		justify-content: space-end;
	}

	.flex-wrap {
		flex-wrap: wrap;
	}

	.mr-30 {
		margin-right: 30rpx
	}

	.mt-30 {
		margin-top: 30rpx;
	}

	.mb-30 {
		margin-bottom: 30rpx;
	}

	.f-28 {
		font-size: 28rpx;
	}

	.col-2979ff {
		color: #2979ff;
	}

	.spec-value-list {
		width: 100%;
	}

	.spec-name-input {
		padding: 10rpx 20rpx 20rpx 0rpx;
		box-sizing: border-box;
		width: 400rpx;
		height: 70rpx;
	}

	.add-spec-button {
		background-color: #2979ff;
		color: #ffffff;
		height: 80rpx;
		line-height: 80rpx;
		font-size: 30rpx;
		width: 40%;
	}

	.delete-spec-button {
		background-color: #2979ff;
		color: #ffffff;
		margin-top: 24rpx;
	}

	.value-item {
		padding: 10rpx 20rpx 20rpx 0rpx;
		height: 70rpx;
		box-sizing: border-box;
		width: 30%;
	}

	.btn-normal {
		border: none !important;
	}

	.combinations-table {
		margin-top: 20px;
		width: 100%;
		border-collapse: collapse;
	}

	.input-all-button {
		width: 100px;
		height: 20px;
		font-size: 10px;
		line-height: 20px;
		border: none;
		margin-top: 6px;
		color: #2979ff
	}

	.combinations-table th,
	.combinations-table td {
		text-align: center;
		font-weight: 400;
		padding: 10px;
		border: 1px solid #ccc;
	}

	.price-input {
		width: 90%;
		margin: auto;
		padding: 10px;
		border: 1px solid #ccc;
		border-radius: 4px;
	}
</style>